package com.base.common.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

/**
 * Util set
 * 
 * @author xingkong1221
 *
 */
public class Utils {
	
	/**
	 * Calculate the MD5
	 * @param str
	 * @return
	 */
	public static String MD5(String str) {  
       MessageDigest messageDigest = null;  
       try {  
           messageDigest = MessageDigest.getInstance("MD5");  
           messageDigest.reset();  
           messageDigest.update(str.getBytes("UTF-8"));  
       } catch (NoSuchAlgorithmException e) {  
           System.out.println("NoSuchAlgorithmException caught!");  
           System.exit(-1);  
       } catch (UnsupportedEncodingException e) {  
           e.printStackTrace();  
       }  
       byte[] byteArray = messageDigest.digest();  
       StringBuffer md5StrBuff = new StringBuffer();  
       for (int i = 0; i < byteArray.length; i++) {              
           if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)  
               md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));  
           else  
               md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));  
       }  
       return md5StrBuff.toString();  
   }  
	
	/**
	 * Get a random number
	 * @param length
	 * @return
	 */
	public static int getRandom(int length) {
		return (int) Math.random()*(10 * length);
	}
	
	/**
	 * Get remote client real address
	 * @param request
	 * @return
	 */
	public static String getRealAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
	
	
	/**
	 * Formatting date to string
	 * @param data
	 * @param format
	 * @return String 
	 */
	public static String dateToString(Date date, String format) {
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		return formatter.format(date);
	}
	
	/**
	 * Formatting string to date
	 * @param date
	 * @param format
	 * @return
	 * @throws ParseException
	 */
	public static Date StringToDate(String date, String format) throws ParseException {
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		return formatter.parse(date);
	}
}
